package com.wang.luntan.common.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.wang.luntan.common.pojo.ApiResponseEnum;
import com.wang.luntan.common.util.ConstatFinalUtil;
import com.wang.luntan.common.util.DateFormatUtil;
import com.wang.luntan.common.util.EncryptUtil;
import com.wang.luntan.common.util.FileUtil;
import com.wang.luntan.common.util.HttpUtil;
import com.wang.luntan.common.util.PageInfoUtil;
import com.wang.luntan.common.util.RedisUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 所有Controller的父类
 *
 * @author WangshSxt
 */
@Log4j2
public class BaseController {
    @Autowired
    protected DateFormatUtil dateFormatUtil;
    @Autowired
    protected EncryptUtil encryptUtil;
    @Autowired
    protected FileUtil fileUtil;
    @Autowired
    protected HttpUtil httpUtil;
    @Autowired
    protected RedisUtil redisUtil;
    /**
     * 页面上提示信息默认为null
     */
    protected String info = ConstatFinalUtil.INFO_JSON.getString(ApiResponseEnum.STATUS_FAILED.getName());

    /**
     * 公共的一些操作
     *
     * @param request
     * @return
     */
    protected void commonOper(HttpServletRequest request) {
        /* 存储一些公共的变量
         * websiteUrl(网络路径),http://127.0.0.1:8080/usersCenter-web-head/
         * websiteFileUrl(网路路径),http://127.0.0.1:8080/usersCenter-web-head/
         * */
        request.setAttribute("websiteUrl", ConstatFinalUtil.CONFIG_JSON.get("website.url"));
        request.setAttribute("websiteFileUrl", ConstatFinalUtil.CONFIG_JSON.get("website.fileUrl"));
    }

    /**
     * 生成分页对象
     *
     * @param currentPage 当前页
     * @param pageSize    每页有多少条
     * @return
     */
    protected PageInfoUtil proccedPageInfo(String currentPage, String pageSize) {
        /* 分页 默认每页有10条*/
        PageInfoUtil pageInfoUtil = new PageInfoUtil();
        try {
            /* 将字符串转换成整数,有风险,
             * 字符串为a,转换不成不整数
             *  */
            pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));
            pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
        } catch (NumberFormatException e) {
        }
        return pageInfoUtil;
    }

    /**
     * 生成一个查询列表公共的搜索条件
     *
     * @param request
     * @return
     */
    protected Map<String, Object> proccedSearch(HttpServletRequest request) {
        Map<String, Object> condMap = new HashMap<String, Object>();
        String keyword = request.getParameter("keyword");
        String status = request.getParameter("status");
        String st = request.getParameter("st");
        String ed = request.getParameter("ed");
        /* request只是可以查询到但是自己并没有存储所以要将查询条件存储到request中 */
        request.setAttribute("keyword", keyword);
        request.setAttribute("status", status);
        request.setAttribute("st", st);
        request.setAttribute("ed", ed);
        /* 关键字 */
        if (keyword == null) {
            keyword = "";
        }
        /* 状态 */
        if (status == null) {
            status = "";
        }
        /* 查询的起始时间和结束时间 */
        Date stDate = null;
        Date edDate = null;
        if (st != null && !"".equalsIgnoreCase(st) && ed != null && !"".equalsIgnoreCase(ed)) {
            stDate = this.dateFormatUtil.strDateTime(st);
            edDate = this.dateFormatUtil.strDateTime(ed);
        }
        condMap.put("keyword", keyword);
        condMap.put("status", status);
        condMap.put("stDate", stDate);
        condMap.put("edDate", edDate);
        return condMap;
    }

    /**
     * 生成分页对象
     *
     * @param request
     * @return
     */
    protected PageInfoUtil proccedPageInfo(HttpServletRequest request) {
        String currentPage = request.getParameter("currentPage");
        String pageSize = request.getParameter("pageSize");
        /* 分页 */
        PageInfoUtil pageInfoUtil = new PageInfoUtil();
        try {
            /* 将字符串转换成整数,有风险,
             * 字符串为a,转换不成不整数
             *  */
            pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));
            pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
            return pageInfoUtil;
        } catch (NumberFormatException e) {
        }
        return pageInfoUtil;
    }

    /**
     * 从session中获取用户或者管理员信息
     *
     * @return
     */
    protected Object findObjfromSession(HttpServletRequest request, String type) {
        HttpSession session = request.getSession();
        if ("users".equalsIgnoreCase(type)) {
            return session.getAttribute("users");
        } else if ("admins".equalsIgnoreCase(type)) {
            return session.getAttribute("admins");
        }
        return null;
    }

    /**
     * 返回json字符串
     *
     * @param request
     * @param returnStr
     * @return
     */
    public JSONObject printOut(HttpServletRequest request, HttpServletResponse response, String returnStr) {
        try {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print(returnStr);
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error("为客户端返回信息出错了;", e);
        }
        return null;
    }

    /**
     * 获取ip
     *
     * @param request
     * @return
     */
    public String getIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Real-IP");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
            //根据网卡取本机配置的IP
            InetAddress inet = null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            ipAddress = inet.getHostAddress();
        }
        return ipAddress;
    }

    /**
     * 生成验证码
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("/info")
    public String info(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("==info==");
        return "/info";
    }
}
